package com.ahcloud.edas.gatewaylog.biz.application.helper;

import com.ahcloud.edas.common.exception.BizException;
import com.ahcloud.edas.gatewaylog.biz.domain.log.query.LogListQuery;
import com.ahcloud.edas.gatewaylog.biz.domain.log.query.LogQuery;
import com.ahcloud.edas.gatewaylog.biz.infrastructure.constant.LogConstants;
import com.ahcloud.edas.gatewaylog.client.exception.LogRetCodeEnum;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Objects;

/**
 * @program: ahcloud-operatelog
 * @description:
 * @author: YuKai Fan
 * @create: 2024/6/6 13:32
 **/
public class LogParamChecker {

    public static void checkLogQuery(LogQuery query, boolean checkId) {
        if (StringUtils.isBlank(query.getApiCode())) {
            throw new BizException(LogRetCodeEnum.PARAM_MISS, "apiCode");
        }
        if (StringUtils.isBlank(query.getEnv())) {
            throw new BizException(LogRetCodeEnum.PARAM_MISS, "env");
        }
        if (checkId && query.getId() == null) {
            throw new BizException(LogRetCodeEnum.PARAM_MISS, "id");
        }
    }

    public static void checkLogListQuery(LogListQuery query) {
        checkLogQuery(query, false);
        // 判断当前时间段是否在3天内
        if (Objects.nonNull(query.getStartTime()) && Objects.nonNull(query.getEndTime())) {
            if (query.getStartTime().isAfter(query.getEndTime())) {
                throw new BizException(LogRetCodeEnum.PARAM_ILLEGAL_FIELD, "开始时间不能大于结束时间");
            }
            // 判断当前时间段是否在7天前
            if (query.getStartTime().isBefore(LocalDateTime.now().minusDays(LogConstants.LOG_STORAGE_DAY))) {
                throw new BizException(LogRetCodeEnum.TIME_PERIOD_ERROR, "不能查询7天前的数据");
            }
            // 判断当前时间段是否在7天前
            if (query.getEndTime().isBefore(LocalDateTime.now().minusDays(LogConstants.LOG_STORAGE_DAY))) {
                throw new BizException(LogRetCodeEnum.TIME_PERIOD_ERROR, "不能查询7天前的数据");
            }
            if (toMilli(query.getEndTime()) - toMilli(query.getStartTime()) > LogConstants.LOG_QUERY_TIME) {
                throw new BizException(LogRetCodeEnum.TIME_PERIOD_ERROR, "时间段间隔不能超过3天");
            }
        }
    }

    private static long toMilli(LocalDateTime localDateTime) {
        return localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
    }
}
